<template>
  <div class="model">
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <div class="lonin">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <section class="nav">
        <a
          href="javascript:;"
          :class="{ active: isShowphone }"
          @click="isShowphone = true"
          >手机登录</a
        >|
        <a href="javascript:;" :class="{ active: !isShowphone }" @click="showQr"
          >微信登录</a
        >
      </section>
      <div class="content">
        <div class="phonebox" v-show="isShowphone">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imgsarr"
            ></slide-verify>
          </div>
          <div class="row">
            <input type="text" placeholder="请输入验证码" v-model="phonecode" />
            <button class="btncode" @click="getcode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btncode" v-show="isShowCount">
              {{ count }}
            </button>
          </div>
          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <div class="qrbox" v-show="!isShowphone" id="weixin">微信登录</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import { validatePhoneNumber } from "@/utils";
import {
  SendSMSAPI,
  PhoneReginAPI,
  bangdingAPI,
  UserProfilesAPI,
} from "@/request/api.js";
export default {
  data() {
    return {
      isShowphone: true,
      msg: "向右滑动",
      imgsarr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
      // 手机号
      phoneNumber: "",
      //验证时间
      count: 60,
      isShowCount: false,
      phonecode: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showmodel/changeIsShowLoginModal",
      changeisShowlogStatus: "logStatus/changeisShowlogStatus",
      // changeshowToast: "showToast/changeshowToast",
    }),
    ...mapActions({
      asyncIsshow: "showToast/asyncIsshow",
      asyncchangeuserInfo: "userInfo/asyncchangeuserInfo",
    }),
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    //封装验证函数
    togetcode() {
      //1.先判断用户是否输入正确的手机号,用正则表达式
      //teg.test(str) 验证是否符合规则,如果符合返回true,否则返回false
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确手机号");
        // this.changeshowToast({
        //   isshow: true,
        //   msg: "请输入正确手机号",
        //   type: "danger",
        // });
        // setTimeout(() => {
        //   this.changeshowToast(false);
        // }, 2000);
        this.asyncIsshow({
          isshow: true,
          msg: "请输入正确手机号",
          type: "danger",
        });
        return;
      }
      // 2.判断验证滑块
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        // alert("请滑动验证码");
        this.asyncIsshow({
          isshow: true,
          msg: "请滑动滑块",
          type: "danger",
        });
        return;
      }
      return true;
    },
    //获取验证码
    async getcode() {
      //3.发送验证码

      //判断封装的验证函数传过来的值是undefind还是ture,都验证成功了就是ture可以进行发验证码,返回undefind就是结束后面运行
      let flag = this.togetcode();
      if (!flag) return;
      //发送验证码请求
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      // console.log("res", res);
      if (!res) return;
      if (res.code == 0) {
        //验证码倒计时
        this.isShowCount = true;
        let time = setInterval(() => {
          this.count--;

          if (this.count == 0) {
            clearInterval(time);
            this.count = 60;
            this.isShowCount = false;
          }
        }, 1000);
      }
    },
    //登录
    async submitFn() {
      //前面条件是否通过
      if (!this.togetcode()) return;
      //判断验证码不为空
      if (this.phonecode == "") {
        this.asyncIsshow({
          isshow: true,
          msg: "请输入验证码再进行登录",
          type: "danger",
        });
        return;
      }
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        //判断微信是否第一次登录,是就执行绑定
        res = await bangdingAPI({
          verifyCode: this.phonecode,
          phone: this.phoneNumber,
          uuid,
        });
        // console.log("uuid");
      } else {
        //前面条件都通过则发送手机登录请求
        res = await PhoneReginAPI({
          verifyCode: this.phonecode,
          phone: this.phoneNumber,
        });
        // console.log("sjh");
      }
      if (!res) return;
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      //登录一分钟后删除token
      let token = localStorage.getItem("x-auth-token");
      if (token) {
        setInterval(() => {
          localStorage.removeItem("x-auth-token");
        }, 600000);
      }
      this.changeIsShowLoginModal(false);
      this.changeisShowlogStatus(true);
      localStorage.removeItem("uuid");
      this.asyncchangeuserInfo();
    },
    showQr() {
      this.isShowphone = false;
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9",
      });
    },
  },
};
</script>

<style lang='less' scoped>
.model {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.3);
  }
  .lonin {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    text-align: center;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 55px;
      top: 10px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
    }
    .nav {
      margin-top: 40px;
      font-size: 18px;
      a {
        text-decoration: none;
        color: gray;
        &.active {
          color: #000;
        }
      }
    }
    .content {
      width: 355px;
      margin: 10px auto 0;
      .phonebox {
        margin-top: 20px;
        .row {
          display: flex;
          margin-bottom: 20px;
          input {
            flex: 1;
            height: 50px;
            text-indent: 1em;
            outline: none;
          }
          button {
            height: 50px;
            background-color: #0a328e;
            color: #fff;
            font-size: 16px;
            border: none;
          }
          .btncode {
            margin-left: 10px;
            height: 55px;
            width: 92px;
          }
          .btnlogin {
            width: 100%;
          }
        }
      }
    }
  }
  /deep/.slide-box {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    canvas {
      position: absolute;
      left: 0;
      top: -120px;
      display: none;
      width: 100%;
      box-sizing: border-box;
    }
    .slide-verify-block {
      width: 85px;
      height: 136px;
    }
    .slide-verify-refresh-icon {
      top: -120px;
      display: none;
    }
    &:hover {
      canvas {
        display: block;
      }
      .slide-verify-refresh-icon {
        display: block;
      }
    }
  }
}
</style>